package com.example.java_second_hand_market;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;
import java.sql.*;

public class RegisterDialog extends Stage {
    @FXML
    Label nameLabel = new Label("姓名: ");
    @FXML
    TextField nameName = new TextField();
    @FXML
    Label userLabel = new Label("用户名: ");
    @FXML
    TextField userName = new TextField();
    @FXML
    Label passLabel = new Label("密  码: ");
    @FXML
    PasswordField userPassword = new PasswordField();
    @FXML
    Label comfirmpassLabel = new Label("确  认  密  码: ");
    @FXML
    PasswordField comfirmuserPassword = new PasswordField();
    @FXML
    Label sfLabel = new Label("身份：");
    @FXML
    RadioButton BuyerRB = new RadioButton("买家");
    @FXML
    RadioButton SellerRB = new RadioButton("商家");
    @FXML
    RadioButton adminRB = new RadioButton("管理员");
    @FXML
    Button loginButton = new Button("登录", new ImageView());
    @FXML
    Button quitButton = new Button("退出", new ImageView());
    @FXML
    Button registerButton = new Button("注册",new ImageView());
    String userId;
    MainMarket appUser;

    String DBUrl=ParameterDB.ParaDBUserUrl;
    String DBUser="root", DBPassword="123456";
    public RegisterDialog(MainMarket app, int width, int height){
        appUser = app;
        userName.setPrefWidth(150);
        userPassword.setPrefWidth(150);
        userName.setEditable(true);
        registerButton.setStyle("-fx-text-fill:red");
        loginButton.setOnAction(new EventHandler<ActionEvent>()

        {   @Override
            public void handle(ActionEvent e)
        {   close();
            LoginDialog ld=new LoginDialog(appUser,width,height);

        }
        });

        quitButton.setOnAction(new EventHandler<ActionEvent>()
        {   public void handle(ActionEvent e)
        {	close();
            Platform.exit();
        }
        });
        registerButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
            registeraction();
            }
        });
        VBox vb = new VBox();
        vb.setSpacing(10);

        HBox hb6 = new HBox();
        hb6.getChildren().addAll(nameLabel, nameName);
        hb6.setMargin(nameLabel, new Insets(3,0,0,0));
        hb6.setMargin(nameName, new Insets(0,0,0,3));

        HBox hb1 = new HBox();
        hb1.getChildren().addAll(userLabel, userName);
        hb1.setMargin(userLabel, new Insets(3,0,0,0));
        hb1.setMargin(userName, new Insets(0,0,0,3));

        HBox hb2 = new HBox();
        hb2.getChildren().addAll(passLabel, userPassword);
        hb2.setMargin(passLabel, new Insets(3,0,0,0));
        hb2.setMargin(userPassword, new Insets(0,0,0,6));

        HBox hb5 = new HBox();
        hb5.getChildren().addAll(comfirmpassLabel, comfirmuserPassword);
        hb5.setMargin(comfirmpassLabel, new Insets(3,0,0,0));
        hb5.setMargin(comfirmuserPassword, new Insets(0,0,0,6));

        HBox hb3 = new HBox();
        hb3.getChildren().addAll(sfLabel, BuyerRB, SellerRB, adminRB);
        hb3.setSpacing(5);
        hb3.setMargin(sfLabel, new Insets(2,0,0,0));
        hb3.setMargin(BuyerRB, new Insets(0,0,0,5));

        ToggleGroup tg = new ToggleGroup();
        BuyerRB.setToggleGroup(tg);
        SellerRB.setToggleGroup(tg);
        adminRB.setToggleGroup(tg);

        HBox hb4 = new HBox();
        hb4.setSpacing(20);
        hb4.setAlignment(Pos.CENTER);
        hb4.getChildren().addAll(loginButton, quitButton,registerButton);

        vb.getChildren().addAll(hb6, hb1, hb2, hb5, hb3);

        BorderPane bPane = new BorderPane();
        bPane.setCenter(vb);
        bPane.setBottom(hb4);
        bPane.setPadding(new Insets(15,40,20,40));

        setX(820);
        setY(500);
        initModality(Modality.APPLICATION_MODAL);
        setScene(new Scene(bPane));

        setWidth(400);
        setHeight(300);
        setX((width-getWidth()) / 2);
        setY((height-getHeight())/ 2);
        setTitle("注册系统");
        show();
    }

    public void registeraction(){
        String name=(nameName.getText()).trim();
        userId = (userName.getText()).trim();
        String pw = (userPassword.getText()).trim();
        String cpw= (comfirmuserPassword.getText()).trim();
        try
        {   Connection con = DriverManager.getConnection(DBUrl, DBUser, DBPassword);
            Statement stmt = con.createStatement();
            if((pw==null || cpw.equals(pw)))
            {int isad;
                if(adminRB.isSelected()==true){
                isad=1;
            }else{
                    isad=0;
                }
                if(userId.length() == 0)
                {   CommonDialog.WarningDialog("请输入用户名！");
                    userName.clear();
                    return;
                }
                if(name.length()>20){
                    CommonDialog.WarningDialog("名字太长！");
                    nameName.clear();
                    return;
                }
                if(userId.length()>20){
                    CommonDialog.WarningDialog("用户名太长");
                    userName.clear();
                    return;
                }
                if(pw.length()>20){
                    CommonDialog.WarningDialog("密码太长！");
                    userPassword.clear();
                    comfirmuserPassword.clear();
                    return;
                }
                ResultSet rs=stmt.executeQuery("SELECT * FROM user_list WHERE name = '"+name+"' OR account = '"+userId+"'");
                if(rs.next()){
                    CommonDialog.WarningDialog("用户名重复！");
                    userName.clear();

                    try{
                        rs.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                    return;
                }

                try{
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                stmt.executeUpdate("INSERT INTO user_list ( name, account, password, is_ban, is_admin)" +
                    "VALUES ( '"+name+"', '"+userId+"', '"+pw+"', 0, "+isad+");");



                    if(BuyerRB.isSelected())
                    {
                        appUser.loginasbuyer(name,userId,pw);
                    }
                    if(SellerRB.isSelected())
                    {   appUser.loginasseller(name,userId,pw);
                    }
                    if(adminRB.isSelected())
                    {   appUser.loginasadmin(name,userId,pw);
                    }



                    if(con!=null) {
                       try {
                           stmt.close();
                           con.close();

                       }catch (SQLException err){
                           System.out.println("18787");
                       }
                        close();
                    }
                }
                else

                    CommonDialog.WarningDialog(" 请重新确认密码！");



            if(con!=null) {
                try {
                    stmt.close();
                    con.close();

                }catch (SQLException err){
                    System.out.println("1999");
                }
            }
        }
        catch(SQLException s)
        {   System.out.println("不能打开 management， 数据库操作失败！"+s.getSQLState()+s.getMessage()+s.getErrorCode());
        }
    }
}
